﻿using System;
using System.Data;
using System.IO;
using System.Windows;
using Microsoft.Win32;


namespace CSVFormater
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        #region Decliaration
        private string _fileCsv;		//full file name
        private string _dirCsv;		//directory of file to import
        private string _fileNevCsv;	//name (with extension) of file to import - field
        private DataSet _tempDataSet;

        public string FileNevCSV	//name (with extension) of file to import - property
        {
            get { return _fileNevCsv; }
            set { _fileNevCsv = value; }
        }

        private string strFormat;	//CSV separator character
        private string strEncoding; //Encoding of CSV file

        private long rowCount = 0;	//row number of source file

        #endregion

        #region Events handler

        private void BtnFileOpenClick(object sender, RoutedEventArgs e)
        {
            var openFileDialogCsv = new OpenFileDialog();
            openFileDialogCsv.InitialDirectory = Environment.CurrentDirectory;
            openFileDialogCsv.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
            openFileDialogCsv.FilterIndex = 1;
            openFileDialogCsv.RestoreDirectory = true;
            if(openFileDialogCsv.ShowDialog()== true)
            {
                txtFileToImport.Text = openFileDialogCsv.FileName;
            }
        }

        private void BtnPreview(object sender, RoutedEventArgs e)
        {
            LoadPreview();
            this.groupBoxSecondStep.IsHitTestVisible = true;
            this.groupBoxSecondStep.Opacity = 1;
            this.groupBoxFirstStep.IsHitTestVisible = false;
            this.groupBoxFirstStep.Opacity = 0.5;
        }

        #endregion
        /* Loads the preview of CSV file in the DataGridView control.
        */

        private void LoadPreview()
        {
            try
            {
                // select format, encoding, an write the schema file
                Format();
                Encoding();
                WriteSchema();
                
                // loads the first 500 rows from CSV file, and fills the
                // DataGridView control.
                _tempDataSet = LoadCsv(500);
                dataGrid_preView.DataSource = _tempDataSet;
                this.dataGrid_preView.DataMember = "csv";
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error - loadPreview");
            }
        }

        // Delimiter character selection
        private void Format()
        {
            try
            {
                if (rdbSemicolon.IsChecked != null)
                    if ((bool)rdbSemicolon.IsChecked)
                    {
                        strFormat = "Delimited(;)";
                    }
                    else if (rdbTab.IsChecked != null)
                        if ((bool)rdbTab.IsChecked)
                        {
                            strFormat = "TabDelimited";
                        }
                        else if (rdbSeparatorOther.IsChecked != null)
                            if ((bool)rdbSeparatorOther.IsChecked)
                            {
                                strFormat = "Delimited(" + txtSeparatorOtherChar.Text.Trim() + ")";
                            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Format");
            }
        }


        // Encoding selection
        private void Encoding()
        {
            try
            {
                if (rdbAnsi.IsChecked != null)
                    if ((bool) rdbAnsi.IsChecked)
                    {
                        strEncoding = "ANSI";
                    }
                    else if (rdbUnicode.IsChecked != null)
                        if ((bool) rdbUnicode.IsChecked)
                        {
                            strEncoding = "Unicode";
                        }
                        else if (rdbOEM.IsChecked != null)
                            if ((bool) rdbOEM.IsChecked)
                            {
                                strEncoding = "OEM";
                            }
                            else
                            {
                                strEncoding = "ANSI";
                            }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Encoding");
            }
        }


        public DataSet LoadCsv(int numberOfRows)
        {
            return CSVLoader.LoadCsv(_dirCsv, _fileNevCsv);
        }

        private void TbFileTextChanged(object sender, EventArgs e)
        {
            // full file name
            this._fileCsv = this.txtFileToImport.Text;

            // creates a System.IO.FileInfo object to retrive information from selected file.
            var fi = new System.IO.FileInfo(this._fileCsv);
            // retrives directory
            this._dirCsv = fi.DirectoryName.ToString();
            // retrives file name with extension
            this.FileNevCSV = fi.Name.ToString();

            // database table name
            //this.txtTableName.Text = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length).Replace(" ", "_");
        }


        /* Schema.ini File (Text File Driver)

		When the Text driver is used, the format of the text file is determined by using a
		schema information file. The schema information file, which is always named Schema.ini
		and always kept in the same directory as the text data source, provides the IISAM 
		with information about the general format of the file, the column name and data type
		information, and a number of other data characteristics*/
        private void WriteSchema()
        {
            try
            {
                var fsOutput = new FileStream(this._dirCsv + "\\schema.ini", FileMode.Create, FileAccess.Write);
                var srOutput = new StreamWriter(fsOutput);
                string s1, s2, s3, s4, s5;

                s1 = "[" + this.FileNevCSV + "]";
                s2 = "ColNameHeader=" + chkFirstRowColumnNames.IsChecked.ToString();
                s3 = "Format=" + this.strFormat;
                s4 = "MaxScanRows=25";
                s5 = "CharacterSet=" + this.strEncoding;

                srOutput.WriteLine(s1.ToString() + "\r\n" + s2.ToString() + "\r\n" + s3.ToString() + "\r\n" + s4.ToString() + "\r\n" + s5.ToString());
                srOutput.Close();
                fsOutput.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "writeSchema");
            }
            finally
            { }
        }

        private void BackStep(object sender, RoutedEventArgs e)
        {
            this.groupBoxFirstStep.IsHitTestVisible = true;
            this.groupBoxFirstStep.Opacity = 1;
            this.groupBoxSecondStep.IsHitTestVisible = false;
            this.groupBoxSecondStep.Opacity = 0.5;
        }

        private void ComboBoxDataContextChanged(object sender, EventArgs eventArgs)
        {
            if (this.comboBoxKnownBusiness.SelectedIndex == 0)
            {
                rdbTab.IsChecked = true;
                rdbUnicode.IsChecked = true;
                chkFirstRowColumnNames.IsChecked = true;
            }
            else if(this.comboBoxKnownBusiness.SelectedIndex == 1)
            {
                rdbSeparatorOther.IsChecked = true;
                txtSeparatorOtherChar.Text = ",";
                rdbAnsi.IsChecked = true;
                chkFirstRowColumnNames.IsChecked = true;
            }
        }

        private void ButtonReadyToExportClick(object sender, RoutedEventArgs e)
        {
            
            new Converter(_tempDataSet).Show();
            this.Close();
        }
    }

}
